#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#define err_exit(msg) (perror(msg), exit(-1))
/*
********************函数功能：实现文件重定向****************************
*/
void main()
{
    FILE *stream;     //文件指针
    char buffer[128]; //128B的缓冲区
    printf("create test_file.\n");
    //创建文件test_file
    if ((stream = fopen("test_file", "w")) == NULL)
        err_exit("open failed.");
    //将HELLO WORLD写入文件
    printf("write string to test_file\n");
    fputs("HELLO WORLD", stream);
    fclose(stream); //关闭文件流以保存
    //重定向文件stdin重定向到文件test_file
    if (freopen("test_file", "r", stdin) == NULL)
        err_exit("redirect failed.");
    //读入数据
    printf("read string from test_file.\n");
    fgets(buffer, sizeof(buffer), stdin);
    //输出结果
    printf("the string is %s\n", buffer);
}